package com.cos.lession73.slice;

import com.cos.lession73.ResourceTable;
import com.cos.lession73.entity.City;
import com.cos.lession73.provider.CityProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        //1 获取 ListContainer 对象
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_myContanier);
        //2 获取数据
        List<City> listData = createListData();
        //3 实例化cityProvider 传入生成的列表数据 以及 当前有ListContainer的slice实例
        CityProvider cityProvider = new CityProvider(listData,this);
        //4 把cityProvider提供的组件加入到Listcontainer当中
        listContainer.setItemProvider(cityProvider);
        //5 监控组件数据的加载
        listContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                //调用 provider的数据更新方法
                cityProvider.notifyDataChanged();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {

            }
        });

        //6 设置监听 ListContainer里面子项的点击监听
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                //通过listContainer获取Provider,在通过Provider来获取被点击数据对象

               City c = (City) listContainer.getItemProvider().getItem(i);
               new ToastDialog(getContext()).setText("点击的是"+c.getCityName())
                       .setDuration(5000).setAlignment(LayoutAlignment.CENTER)
                       .show();
            }
        });

    }
    //生成假数据的方法
    private List<City> createListData(){
        List<City> list = new ArrayList<>();

        for (int i = 0; i < 100; i++) {
            list.add(new City("城市:"+i));
        }
        return list;
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
